package arrays;

public class Array03 {
    public static void main(String[] args) {
        int[] array = {1,2,3,4,5,6,7,8,9,10};
        System.out.println(binarySearch(array, 5));
        System.out.println(binarySearch(array, 11));

    }

    //二分查找
    public static int binarySearch(int[] array, int target) {
        //左边界
        int left = 0;
        //右边界
        int right = array.length - 1;

        while (left <= right) {
            int mid = (left + right) / 2;
            // 找到目标值
            if (array[mid] == target) {
                return mid;
            // 目标在右半区
            } else if (array[mid] < target) {
                // 继续向右查找
                left = mid + 1;
            } else {
                // 目标在左半区
                right = mid - 1;
            }
        }
        // 没找到
        return -1;
    }
}
